#!usr/bin/env python3
# -*- coding: utf-8 -*-

#socketClient
import socket,time

class SocketClient(object):
	def __init__(self,ip,port):
		self._ip = ip
		self._port = int(port)
		self.max = 1024
		self.createSocket()
		
	def createSocket(self):
		self._sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
		self._sk.connect((self._ip,self._port))
		self._sk.setblocking(0)
	
	def send(self,content):
		self._sk.send(content.encode('utf-8')) #发送的数据必须是byte类型
		self.recvData();
		print('recvData:end')
		
	def recvData(self):
		bufs = [];
		flag = True
		while flag:			
			
			try:
				d = self._sk.recv(self.max)
			except:				
				time.sleep(2) #模拟一个阻塞
				print('进入异常:',d)
				continue
				
			if d and len(d)>0 and d!='0' and d!=0:
				print('recvData:recv from %s data: %s'%(str(self._ip),d.decode('utf-8')))
				bufs.append(d.decode('utf-8'))				
			else:
				print('recvData:data end')
				flag = False
				break
			
		print('bufs=',bufs)
		
		
		
print("this is socket client opening .... ")
				
ip = '127.0.0.1' #input('ip addr:')
port = '9999' #input('port:')

sk = SocketClient(ip,port)

clientHead="C2S_HI_"

while True:	
	content = input('send what:')
	clientHead+=content
	sk.send(content)	
	if content=='Q':
		break;


		